package com.ruijie.autotest.log.validation.hangzhoudewangxin.HBDEV;

import com.minelx.landisk.filesystem.Paths;
import com.minelx.landisk.filesystem.core.Directory;
import com.minelx.landisk.filesystem.core.File;
import com.ruijie.autotest.log.common.crypto.*;
import com.ruijie.autotest.log.impl.parse.ColumnsAndValuesParser;
import com.ruijie.autotest.log.impl.parse.GridColumnsParser;
import com.ruijie.autotest.log.impl.parse.LinesParser;
import com.ruijie.autotest.log.impl.parse.ReduceEndCellsParser;
import com.ruijie.autotest.log.validation.hangzhoudewangxin.WIFILOGOUT.SingleValuesFileToTable;
import com.ruijie.autotest.log.validation.hangzhouxiruan.IVerification;
import com.ruijie.autotest.log.validation.hangzhouxiruan.CompositeColumnVerification;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

import java.util.List;

import static com.minelx.landisk.filesystem.core.File.byExtension;

@SpringBootConfiguration
public class FTPVerificationConfig {
	@Value("${NetSupervisor.ftp.desPassword}")
	private String PASSWORD;

	@Value("${NetSupervisor.ftp.ivPassword}")
	private String IV_PASSWORD;

	@Value("${NetSupervisor.ftp.columnsFilePath}")
	private String columnsFilePath;

	@Value("${NetSupervisor.ftp.zipFilesRootPath}")
	private String zipFilesRootPath;

	private final ApplicationContext context;

	public FTPVerificationConfig(ApplicationContext context) {
		this.context = context;
	}

	@Bean
	IVerification verification() throws Exception {
		SingleValuesFileToTable fileToTable = new SingleValuesFileToTable(
				new ColumnsAndValuesParser(
						new GridColumnsParser(" ", 0),
						new LinesParser("\r\n|\n"),
						new ReduceEndCellsParser("\u0001")),
				Paths.of(columnsFilePath)
		);

		// FIXME 2021/1/16  wait for me!!!   AES to CryptoFactory
		List<File> decryptedFiles = ICryptoFactory.decryptedFiles(
				rawFiles(),
				CBC.create(new AESSha1Algorithm(), PASSWORD, IV_PASSWORD, Padding.PKCS_5_PADDING).cryptoFactory().decryption()
		);

		return new CompositeColumnVerification(context, fileToTable.mapToTables(decryptedFiles));
	}

	private List<File> rawFiles() {
		Directory rootDirectory = Paths.root(zipFilesRootPath);
		return rootDirectory.childrenFiles()
				.filter(which -> !which.getName().startsWith("decrypted_")) // not starts with "decrypted_"
				.filter(byExtension("zip")).all();
	}
}
